const beautify = require('js-beautify').html

function removeComments(html) {
  return (
    html
      // 删除 HTML 注释 <!-- -->
      .replace(/<!--[\s\S]*?-->/g, '')
      // 删除 JS 单行注释 //...（需小心 false positive）
      .replace(/(^|\s)\/\/.*/g, '')
      // 删除 JS 多行注释 /* ... */
      .replace(/\/\*[\s\S]*?\*\//g, '')
  )
}

module.exports = () => {
  const defaultOptions = {
    indent_size: 2,
    preserve_newlines: true,
    max_preserve_newlines: 0
  }

  return (req, res, next) => {
    const originalRender = res.render
    res.render = function (view, renderOptions = {}, callback) {
      originalRender.call(res, view, renderOptions, function (err, html) {
        if (err) {
          return callback ? callback(err) : req.next(err)
        }
        try {
          let formattedHTML = removeComments(html)
          formattedHTML = beautify(formattedHTML, defaultOptions)
          if (callback) {
            callback(null, formattedHTML)
          } else {
            res.send(formattedHTML)
          }
        } catch (e) {
          console.warn('[prettyHTML] Beautify failed:', e)
          res.send(html) // fallback: send raw
        }
      })
    }

    next()
  }
}
